package Exception;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class ExceptionTest {
  /*检查异常的简洁方式*/
  @Test(expected= IndexOutOfBoundsException.class)   
  public void empty() {   
       new ArrayList<Object>().get(0);   
  }  
  /*如果你想了解抛出的是哪种异常，除了想检查要符合某个类型之外，还想检查message中携带的特殊信息，或者封装了根因异常*/
  @Test  
  public void testExceptionMessage() {  
      try {  
          new ArrayList<Object>().get(0);  
          fail("Expected an IndexOutOfBoundsException to be thrown");  
      } catch (IndexOutOfBoundsException anIndexOutOfBoundsException) {  
          assertThat(anIndexOutOfBoundsException.getMessage(), is("Index: 0, Size: 0"));  
      }  
  }  
  
  /*应用规则rule，可以更改异常类型（比如同一方法中有两个---但是可能就划分成两个方法了），可以让多个异常测试方法使用，还可以用hamcrest匹配器*/
  @Rule  
  public ExpectedException thrown = ExpectedException.none();  
    
  @Test  
  public void shouldTestExceptionMessage() throws IndexOutOfBoundsException {  
      List<Object> list = new ArrayList<Object>();  
    
      thrown.expect(IndexOutOfBoundsException.class);  
      thrown.expectMessage("Index: 0, Size: 0");  
      list.get(0);  
      Assert.assertEquals(1, list.get(0));  
  }  
}
